import { create, StateCreator } from "zustand"
import _ from 'lodash'
type ChatState = {
  messages: any[];
  setMessages: (messages: any[]) => void;
  addMessage: (message: any) => void;
  clearMessages: () => void;
  sendMessage: (sendContent: string) => void;
  messageLoading: () => void;
  messageFinish: () => void;
  toBottom: () => void;
}
const chatStateImpl: StateCreator<ChatState> = (set, get) => ({
  messages: [] as any[],
  setMessages: (messages: any[]) => set({ messages }),
  addMessage: (message: any) => {
    set((state) => ({ messages: [...state.messages, message] }))
    get().toBottom()
  },
  clearMessages: () => set({ messages: [] }),
  sendMessage: (sendContent: string) => {
    get().addMessage({ content: sendContent, role: "user" })
    get().messageLoading()
    fetch("http://192.168.31.231:8000/api/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        // messages: [
        //   ...(get().messages.filter((item) => item.status !== "loading"))
        // ],
        messages: [
          {
            'role': 'user',
            'content': sendContent
          }
        ],
        model: 'qwen1.5-14b'
      }),
    }).then((res) => {
      res.text().then(value => {
        let value1 = value.replaceAll(/(^"|"$)/g, "")
        console.log("返回的markdown", value1);
        get().messageFinish()
        get().addMessage({ content: value1, role: "assistant" })
      })
    }).catch(err => {
      get().messageFinish()
      console.log(err)
    })
  },
  messageLoading: () => {
    // get().addMessage({ content: "正在生成中...", role: "assistant" })
    get().addMessage({ content: "正在生成中...", role: "assistant", status: 'loading' })
  },
  messageFinish() {
    let message = _.last(get().messages)
    if (message && message.role === 'assistant' && message.status === 'loading') {
      get().messages.pop()
    }
  },
  toBottom() {
    let div: HTMLElement = document.querySelector(".chat-content-style")!;
    div.scrollTop = div.scrollHeight;
  },
})
const useChat = create<ChatState>(chatStateImpl)
export default useChat
